package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.ApprovalGroupData;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Megan on 16/4/11.
 */
public class WeeklyGroupMsg extends CcMsgStructure {

    private static final String TAG = "WeeklyGroupMsg";

    private Message mmCallback;
    private Context mContext;
    private ArrayList<ApprovalGroupData> mGroupDatas;

    public WeeklyGroupMsg(Message callback, Context context) {
        mmCallback = callback;
        mContext = context;
    }

    @Override
    public void onReceive(JSONObject data) {
        mGroupDatas = new ArrayList<ApprovalGroupData>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            JSONArray jsonArray = jsonObject.getJSONArray("groups");
            for (int i = 0; i < jsonArray.length(); i++) {
                ApprovalGroupData groupData = new ApprovalGroupData();
                JSONObject item = jsonArray.getJSONObject(i);
                groupData.setGroup_id(item.getString("group_id"));
                groupData.setGroup_name(item.getString("group_name"));
                groupData.setTodo_count(item.getInt("unread_count"));
                if (item.has("contact_id")){
                    groupData.setContact_id(item.getString("contact_id"));
                    mGroupDatas.add(groupData);
                }
            }
        } catch (JSONException e) {
            Log.d(TAG, "JSONException : " + e.toString());
            e.printStackTrace();
        }

        if (mmCallback != null)

        {
            mmCallback.obj = mGroupDatas;
            mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
            return;
        }

    }

    @Override
    public void onError(int error, Object ret) {
        Log.d(TAG, "onError : " + error + " ret: " + ret);
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }

    }
}